/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tmro.mobile.txtapark.forms;

import java.io.IOException;
import java.util.Calendar;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import net.tmro.mobile.txtapark.HelloMIDlet;

/**
 *
 * @author tmro
 */
class PayForm extends Form implements ItemCommandListener {

    private static final String shortcode = "7275";
    private static final String addr = "sms://" + shortcode;
 
    private final HelloMIDlet midlet;
    private TextField codeTextField;
    private TextField notesTextField;
    private StringItem sendTXTStringItem;

    public PayForm(HelloMIDlet midlet) {
        super("Pay");
        this.midlet = midlet;
    }

    public void createUI() {
        Image image = null;
        try {
            image = Image.createImage("txt-a-park.png");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        this.append(new ImageItem("", image, ImageItem.LAYOUT_NEWLINE_AFTER, "TXT-a-Park"));

        this.append("Type the code to send to " + shortcode + " The notes field is for your own reference (history view).");

        codeTextField = new TextField("Code", "", 160, TextField.NUMERIC);
        this.append(codeTextField);

        this.append("\n");

        notesTextField = new TextField("Notes", "", 160, TextField.ANY);
        this.append(notesTextField);

        this.append("\n");

        sendTXTStringItem = new StringItem("", "Send TXT", StringItem.BUTTON);
        sendTXTStringItem.setDefaultCommand(new Command("Send", Command.OK, 0));
        sendTXTStringItem.setItemCommandListener(this);
        this.append(sendTXTStringItem);

    }

    public void commandAction(Command c, Item item) {
        if (item == sendTXTStringItem) {
            //validate
            if (null == codeTextField.getString() || codeTextField.getString().length() == 0) {
                final Alert alert = new Alert("Validation");
                alert.setString("You need to type the code displayed by the parking machine.");
                Display.getDisplay(midlet).setCurrent(alert, this);

                return;
            }

            try {
                // save to the RMS
                RecordStore recordStore = RecordStore.openRecordStore("txtapark", true);

                Calendar calendar = Calendar.getInstance();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(calendar.get(Calendar.YEAR)).append("-").append(calendar.get(Calendar.MONTH) + 1).append("-").append(calendar.get(Calendar.DAY_OF_MONTH)).append(" ");

                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                switch (dayOfWeek) {
                    case Calendar.MONDAY:
                        stringBuffer.append("Monday ");
                        break;
                    case Calendar.TUESDAY:
                        stringBuffer.append("Tuesday ");
                        break;
                    case Calendar.WEDNESDAY:
                        stringBuffer.append("Wednesday ");
                        break;
                    case Calendar.THURSDAY:
                        stringBuffer.append("Thursday ");
                        break;
                    case Calendar.FRIDAY:
                        stringBuffer.append("Friday ");
                        break;
                    case Calendar.SATURDAY:
                        stringBuffer.append("Saturday ");
                        break;
                    case Calendar.SUNDAY:
                        stringBuffer.append("Sunday ");
                        break;
                }

                int minute = calendar.get(Calendar.MINUTE);
                stringBuffer.append(calendar.get(Calendar.HOUR)).append(":").append(minute < 10 ? ("0" + minute) : ("" + minute)).append(Calendar.AM == calendar.get(Calendar.AM_PM) ? "AM" : "PM");

                stringBuffer.append(" - ").append(codeTextField.getString());

                if(null != notesTextField && notesTextField.getString().length() > 0){
                    stringBuffer.append(" - ").append(notesTextField.getString());
                }

                String dateSent = stringBuffer.toString();
                System.out.println("DateSent to save:" + dateSent);

                int recordId = recordStore.addRecord(dateSent.getBytes(), 0, dateSent.getBytes().length);
                System.out.println("Added record: " + recordId);

                recordStore.closeRecordStore();

                // TODO send text message here
            } catch (RecordStoreException ex) {
                final Alert alert = new Alert("Error");
                alert.setString("Could not save entry to your history. Proceeding with sending the message");
                Display.getDisplay(midlet).setCurrent(alert, this);

                ex.printStackTrace();
            }

            try {
                

                MessageConnection messageConnection = (MessageConnection) Connector.open(addr);
                TextMessage sms = (TextMessage) messageConnection.newMessage(MessageConnection.TEXT_MESSAGE);

                sms.setPayloadText(codeTextField.getString());

                System.out.println(addr);

                messageConnection.send(sms);
                messageConnection.close();

                final Alert alert = new Alert("Message Sent");
                alert.setString("The message was sent. Prepare to pick-up your ticket...");
                Display.getDisplay(midlet).setCurrent(alert, midlet.menuForm);

            } catch (Throwable ex) {
                final Alert alert = new Alert("Error");
                alert.setString("Could not send the text message. Please try the old fashioned way...");
                Display.getDisplay(midlet).setCurrent(alert, this);
                ex.printStackTrace();
            }
        }
    }
}
